﻿using Elsa.Models;
using Mapster;
using Zhp.Entity.Formula;
using Zhp.Entity.SysEnum;
using Zhp.IService.Formula;
using Zhp.Model.Formula;
using Zhp.Service.Base;
using Zhp.SqlSugar.Repository;

namespace Zhp.Service.Formula
{
    public class FormulaDataService : BaseService<FormulaData>, IFormulaDataService
    {
        private readonly string _separator = ";";
        IBaseRepository<FormulaVariable> _formulaVariableRep;
        public FormulaDataService(IBaseRepository<FormulaData> rep, IBaseRepository<FormulaVariable> formulaVariableRep)
        {
            _rep = rep;
            _formulaVariableRep = formulaVariableRep;
        }

        public async Task<List<FormulaDataModel>> Query(FormulaDataSearch search)
        {
            var list = await _rep.GetPageListAsync(x => true, search);

            var resultList = list.Adapt<List<FormulaDataModel>>();
            foreach (var item in resultList)
            {
                item.VariableIdArray = item.VariableIds.Split(_separator);
                item.FormulaKeyArray = item.FormulaKeys.Split(_separator);
                item.FormulaNameArray = item.FormulaNames.Split(_separator);
            }

            return resultList;
        }

        public async Task<bool> Create(FormulaDataEdit p)
        {
            var entity = p.Adapt<FormulaData>();

            await ConvertFormulaData(entity, p);

            return await entity.InsertAsync();
        }

        public async Task<bool> Update(FormulaDataEdit p)
        {
            var entity = await _rep.GetByIdAsync(p.Id);
            if (entity != null)
            {
                p.Adapt(entity);

                await ConvertFormulaData(entity, p);

                return await _rep.UpdateAsync(entity);
            }
            return false;
        }

        private async Task ConvertFormulaData(FormulaData entity, FormulaDataEdit p)
        {
            entity.VariableIds = string.Join(_separator, p.VariableIdArray);
            entity.FormulaKeys = string.Join(_separator, p.FormulaKeyArray);
            entity.FormulaNames = string.Join(_separator, p.FormulaNameArray);
            var variableList = await _formulaVariableRep.GetListAsync(x => x.VariableType == FormulaVariableTypeEnum.Variable && p.VariableIdArray.Contains(x.Id.ToString()));
            if (variableList.DistinctBy(x => x.EntityType).Count() == 1)
            {
                entity.EntityType = variableList.First().EntityType;
            }
        }

        public async Task<bool> Delete(long id)
        {
            return await _rep.DeleteByIdAsync(id);
        }
    }
}
